class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def find_middle_node(head):
    """
    查找链表中间节点：快慢指针，快指针走两步，慢指针走一步
    head：链表头节点
    """
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow

# 测试
# 构建链表：1→2→3→4→5
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
print(find_middle_node(head).val)  # 输出：3
# 构建链表：1→2→3→4
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
print(find_middle_node(head).val)  # 输出：3